<?php
/**
 * Created by PhpStorm.
 * User: gxh
 * Date: 16-12-30
 * Time: 上午9:51
 */
namespace Inbound\Service;
use \Warehouse\Controller\StockInController;

class InboundshipmentplanService extends PublicInfoService
{

    public $Inboundshipmentplandetail = NULL;

    public $AccountSellerSku = NULL;
    //查询记录总数
    public $count = 0;
    //页面展示包含页面样式
    public $page = 0;
    //数据
    public $data = array();

    public $Inboundshipmentplandetail_data = array();
    public $nowtime;

    public $Prepareneedsdetailsshipmentid = null;

    public function __construct($table = '',$param = array())
    {
        $this->nowtime                   = date('Y-m-d H:i:s',time());
        $this->Inboundshipmentplandetail = D('Inboundshipmentplandetail','Model');
        $this->Inboundshipmentplan       = D('Inboundshipmentplan','Model');
        $this->AccountSellerSku          = D('Api/Amazon/AccountSellerSku','Service');
        $this->StockInModel              = D('Warehouse/StockIn','Model');
        $this->Prepareneedsdetailsshipmentid = D('Prepareneedsdetailsshipmentid', 'Model');
    }

    /**
     * @param array $_array
     * @param null  $model
     * @return mixed
     * 平台计划单的创建
     */
    public function create(&$_array = array(),&$model = NULL)
    {
        $model      = $model==NULL?$this->Inboundshipmentplandetail->model:$model;
        $this->data = array(
            'account_id'                         => $_array['account_id'],
            'account_name'                       => $_array['account_name'],
            'site_id'                            => $_array['site_id'],
            //'batch_code'                         => $_array['batch_code'],
            'shipmentid'                         => $_array['shipmentid'],
            'shipment_name'                      => $_array['shipment_name'],
            //'carrier_service_id'                 => $_array['carrier_service_id'],
            'claim_arrive_time'                  => $_array['claim_arrive_time'],
            'destination_fullfillment_center_id' => $_array['destination_fullfillment_center_id'],
            'ship_to_address_id'                 => $_array['ship_to_address_id'],
            'create_user_id'                     => $_array['create_user_id'],
            'create_time'                        => $_array['create_time'],

            'ship_from_address_id'               => $_array['ship_from_address_id'],
            'tranfer_hopper_id'                  => 1,
            'status'                             => 10,
            'merchant_id'                        => PublicInfoService::get_accounts_by_id($_array['account_id'],'merchant_id'),
            'remark'                             => $_GET['remark']
        );
        $this->Inboundshipmentplandetail->add_by_table($this->data,$model);
        if($this->Inboundshipmentplandetail->Inboundshipmentplan_id){

            foreach($_array['detail'] as $detail){
                $this->Inboundshipmentplandetail_data = array(
                    'inbound_shipment_plan_id' => $this->Inboundshipmentplandetail->Inboundshipmentplan_id,
                    'sku'                      => $detail['sku'],
                    'sku_name'                 => $detail['sku_name'],
                    //'sku_virtual'              => $detail['sku_virtual'],
                    'fnsku'                    => $detail['fnsku'],
                    'position'                 => $detail['position'],
                    'quantity'                 => $detail['quantity'],
                    'export_tax_rebate'        => $detail['export_tax_rebate'],
                    'enterprise_dominant'      => $detail['enterprise_dominant'],
                    'hs_code'                  => $detail['hs_code'],
                    'declaration_element'      => $detail['declaration_element'],
                    'sku_cname'                => $detail['sku_cname'],
                    'seller_sku'               => $detail['seller_sku'],
                    'title'                    => PublicInfoService::get_title_by_sellersku($_array['account_id'],$detail['seller_sku']),
                );
                $this->Inboundshipmentplandetail->add_detail_by_table($this->Inboundshipmentplandetail_data,$model);
            }
        }
        if($this->Inboundshipmentplandetail->Inboundshipmentplandetail_id){
            $model->commit();
        }else{
            $model->rollback();
        }
        return $this->Inboundshipmentplandetail->Inboundshipmentplandetail_id;
    }

    /**
     *抓取平台计划单
     */
    public function grab_shipment_plan($_array,$plan,$plan_address,&$model)
    {
        $model      = $model==NULL?$this->Inboundshipmentplandetail->model:$model;
        $this->data = array(
            'account_id'                         => trim($_array['accountid']),
            'account_name'                       => PublicInfoService::get_accounts_by_id(trim($_array['accountid']),'name'),
            'site_id'                            => PublicInfoService::get_siteid_by_accountid(trim($_array['accountid'])),
            'merchant_id'                        => PublicInfoService::get_accounts_by_id(trim($_array['accountid']),'merchant_id'),
            'shipmentid'                         => $plan_address[0][0]['ShipmentId'],
            'shipment_name'                      => $plan_address[0][0]['ShipmentName'],
            'tranfer_hopper_id'                  => 1,
            'status'                             => 10,
            'ship_from_address_id'               => $plan_address[0][0]['ship_from_address_id'],
            'destination_fullfillment_center_id' => $plan_address[0][0]['DestinationFulfillmentCenterId'],
            'create_user_id'                     => $_SESSION['current_account']['id'],
            'create_time'                        => $this->nowtime,

            //页面接收
            'batch_code'                         => $_array['batch_code'],
            'carrier_service_id'                 => $_array['carrier_service_id'],
            'claim_arrive_time'                  => $_array['claim_arrive_time'],
            'ship_to_address_id'                 => $_array['ship_to_address_id'],

            'ship_from_address_detail'           =>//页面展示
                $plan_address[0][0]['ShipFromAddress']['CountryCode'].' '.$plan_address[0][0]['ShipFromAddress']['StateOrProvinceCode'].' '.$plan_address[0][0]['ShipFromAddress']['City'].' '.$plan_address[0][0]['ShipFromAddress']['AddressLine2'].' '.$plan_address[0][0]['ShipFromAddress']['AddressLine1'].' '.$plan_address[0][0]['ShipFromAddress']['Name'].' '.$plan_address[0][0]['ShipFromAddress']['PostalCode'],
        );
        $detail_sku = array();
        foreach($plan as $plan_detail){
            $skuinfo = $this->AccountSellerSku->getActualSkuByAccountIdAndSellerSku(trim($_array['accountid']),array($plan_detail['SellerSKU']));
            $sku_info = PublicInfoService::getSkuCnname($skuinfo[$plan_detail['SellerSKU']]);
           /* echo "<pre/>";
            echo $_array['accountid'];echo $plan_detail['SellerSKU'];
            print_r($skuinfo);
            print_r($sku_info);exit;*/
            $Inboundshipmentplandetail_data = array(
                'fnsku'             => $plan_detail['FulfillmentNetworkSKU'],
                'quantity'          => $plan_detail['QuantityShipped'],
                'title'             => PublicInfoService::get_title_by_sellersku(trim($_array['accountid']),$plan_detail['SellerSKU']),

                'sku'               => $skuinfo[$plan_detail['SellerSKU']],

                'sku_name'          => $sku_info['name'],

                'position'          => $sku_info['place'],
                'hs_code'           => $sku_info['hs_code'],

                'seller_sku'        => $plan_detail['SellerSKU'],
                'export_tax_rebate' => $_array['export_tax_rebate'],
                //页面接收
                //'sku_cname'         => $sku_info['ename_long'],
                //'enterprise_dominant'      => $_array['enterprise_dominant'],
                //'declaration_element'      => $_array['declaration_element'],
                //'sku_virtual'              => $sku_info['sku_virtual'],
            );
            $detail_sku[]                   = $Inboundshipmentplandetail_data;
        }
        $return_data = array(
            'Inbound_shipment_plan'        => $this->data,
            'Inbound_shipment_plan_detail' => $detail_sku
        );
        return $return_data;
    }

    /**
     *抓取确认创建平台计划单
     */
    public function  grab_confirm($_array,$plan_and_detail_data,&$model = NULL)
    {
        $model = $model==NULL?$this->Inboundshipmentplandetail->model:$model;
        $plan_and_detail_data['Inbound_shipment_plan']['batch_code']         = $_array['batch_code'];
        $plan_and_detail_data['Inbound_shipment_plan']['carrier_service_id'] = $_array['carrier_service_id'];
        $plan_and_detail_data['Inbound_shipment_plan']['claim_arrive_time']  = $_array['claim_arrive_time'];
        $plan_and_detail_data['Inbound_shipment_plan']['ship_to_address_id'] = $_array['ship_to_address_id'];
        unset($plan_and_detail_data['Inbound_shipment_plan']['ship_from_address_detail']);
        //1.添加计划单表
        $this->condition = array(
            'account_id'=>$plan_and_detail_data['Inbound_shipment_plan']['account_id'],
            'shipmentid'=>$plan_and_detail_data['Inbound_shipment_plan']['shipmentid']
        );
        $if_exist = $this->get_field_by_param($this->condition, array('id'));
        if ($if_exist) {
            return 404;
            die;
        }
        $this->Inboundshipmentplandetail->add_by_table($plan_and_detail_data['Inbound_shipment_plan'],$model);
        //2.添加计划单详情表
        if($this->Inboundshipmentplandetail->Inboundshipmentplan_id){
            $export_tax_rebate   = explode(',',rtrim($_array['export_tax_rebate'],','));
            $enterprise_dominant = explode(',',rtrim($_array['enterprise_dominant'],','));
            $need_id   = explode(',',rtrim($_array['need_id'],','));
            //更改备货需求状态为已完成
            foreach($need_id as $k =>$v){
                $data['status'] = 80;
                D('Prepareneedsdetail','Model')->prepareNeedsDetails->where("id = $v")->save($data);
            }
            //检测该批次是否全部已完成并修改状态
            D('Prepareneeds', 'Service')->updateBateCodeStatus($_array['batch_code']);
            foreach($plan_and_detail_data['Inbound_shipment_plan_detail'] as $key => $val){
                $val['export_tax_rebate'] = ($export_tax_rebate[$key]=='是')?1:0;

                $val['enterprise_dominant']      = PublicInfoService::getCompanyId($enterprise_dominant[$key]);//公司主体
                $val['inbound_shipment_plan_id'] = $this->Inboundshipmentplandetail->Inboundshipmentplan_id;
                $val['title']                    = addslashes($val['title']);

                $this->Inboundshipmentplandetail->add_detail_by_table($val,$model);

                //插入备货需求明细平台计划单关联表
                $relationship = array(
                    'prepare_needs_details_id' => '',
                    'shipmentid'               => $plan_and_detail_data['Inbound_shipment_plan']['shipmentid'],
                    'plan_num'                 => $val['quantity'],
                    'status'                   => 10
                );
                D('Prepareneeds','Service')->insert_prepare_needs_details_shipmentid($relationship);
//                $where['account_id'] = $_array['accountid'];
//                $where['batch_code'] = $_array['batch_code'];
//                $where['status'] = 50;
//                $data['status'] = 80;
//                D('Prepareneedsdetail','Model')->prepareNeedsDetails->where($where)->save($data);

            }
        }

        if($this->Inboundshipmentplandetail->Inboundshipmentplandetail_id){
            $model->commit();
        }else{
            $model->rollback();
        }
        return 200;
    }


    /**
     * @param array $_array
     * @param array $_param
     * @param null  $model
     * 更新数据
     */
    public function update($_array = array(),$_param = array(),&$model = NULL)
    {
        $model = $model==NULL?$this->Inboundshipmentplandetail->model:$model;
        return $this->Inboundshipmentplandetail->update($_array,$_param);
    }

    /**
     * @param array $_array
     * @param array $_param
     * @param null  $model
     * 更新发货状态
     */
    public function  update_shipment_status($transport_plan_id = '',$status = '')
    {
        $msg = '';
        $condition = array('transport_plan_id' => $transport_plan_id);
        //找出物流单对应的所有计划单
        $plat_plans         = $this->Inboundshipmentplandetail->Inboundshipmentplan->where($condition)
            ->field('id,account_id,shipmentid,destination_fullfillment_center_id')
            ->select();
        $shipmentid_str     = '';
        $shipmentid_api_str = '';
        foreach($plat_plans as $plat_plan){
            //根据id找出计划单所有的计划单明细
            $condition            = array('inbound_shipment_plan_id' => $plat_plan['id']);
            $plat_plans_datails   = $this->Inboundshipmentplandetail->Inboundshipmentplandetail->where($condition)
                ->field('seller_sku,quantity,fnsku')
                ->select();
            $InboundShipmentItems = array();
            foreach($plat_plans_datails as $plat_plans_datail){
                $InboundShipmentItem    = array(
                    'ShipmentId'            => $plat_plan['shipmentid'],
                    'SellerSKU'             => $plat_plans_datail['seller_sku'],
                    'FulfillmentNetworkSKU' => $plat_plans_datail['fnsku'],
                    'QuantityShipped'       => $plat_plans_datail['quantity'],
                    'QuantityReceived'      => '',
                    'QuantityInCase'        => '',
                );
                $InboundShipmentItems[] = $InboundShipmentItem;
            }
            //接口所需参数

            $account_id     = $plat_plan['account_id'];
            $options        = array(
                'ShipmentId'            => $plat_plan['shipmentid'],
                'InboundShipmentHeader' => array(
                    'ShipmentName'                   => time(),
                    'DestinationFulfillmentCenterId' => $plat_plan['destination_fullfillment_center_id'],
                    'LabelPrepPreference'            => 'SELLER_LABEL',
                    'AreCasesRequired'               => FALSE,
                    'ShipmentStatus'                 => 'SHIPPED',
                ),
                'InboundShipmentItems'  => $InboundShipmentItems,
            );
            $shipmentidList = D('Api/Amazon/Inbound','Service')->shipInboundShipment($account_id, $plat_plan['shipmentid']);
            $shipmentid_str .= $plat_plan['shipmentid'].',';
            if(!is_array($shipmentidList)){
                $shipmentid_api_str .= $shipmentidList.',';
                $this->Inboundshipmentplandetail->update(array('id' => $plat_plan['id']),array('status' => $status));//根据自增更改状态
            }else{
                $msg .= $plat_plan['shipmentid'].'调用后台API标记发货失败,'.$shipmentidList['msg']."\n";
                PublicInfoService::insertShipPool($account_id,$plat_plan['shipmentid']);
            }
        }
        $shipmentid_str_arr     = explode(',',rtrim($shipmentid_str,','));
        $shipmentid_api_str_arr = explode(',',rtrim($shipmentid_api_str,','));
        if($msg != ''){
            return array(
                'status' => 500,
                'msg' => $msg.'请联系销售在亚马逊后台手动标记'
            );
        }else{
            return array(
                'status' => 200,
                'msg' => 'success'
            );
        }
    }

    /*
    * 更新
    * $_array 需要更新计划单表的id
    * $status 当前状态
    * $status_to 更改成的状态
    */
    public function update_plan_status($status,$status_to,$where)
    {
        try{
            $update_data = $this->confirm_user_and_time($status_to);
            //1.更新计划单状态
            $plan_data = $this->Inboundshipmentplandetail->update($where,$update_data);
            /*//2.更新 当前更改的计划单  对应的所有明细的 状态
            $plan_data   = $this->Inboundshipmentplandetail
                ->update_detail(array('inbound_shipment_plan_id'=>$plan_id),array('status'=>$status_to));*/
            $this->Inboundshipmentplandetail->model->commit();
            return $plan_data;
        }catch(Exception $e){
            $this->Inboundshipmentplandetail->model->rollback();
            print $e->getMessage();
            return 0;
        }
    }

    /*
     *状态变更需存入数据库的角色和时间
     */
    public function confirm_user_and_time($status_to)
    {
        switch($status_to){
            case 15:
                $confirm_user_and_time = array(
                    'status'                 => $status_to,
                    'push_warehouse_user_id' => $_SESSION['current_account']['id'],
                    'push_warehouse_time'    => $this->nowtime,
                );
                break;
            case 20:
                $confirm_user_and_time = array(
                    'status'                 => $status_to,
                    'picking_user_id' => $_SESSION['current_account']['id'],
                    'picking_user_time'    => $this->nowtime,
                );
                break;
            case 40:
                $confirm_user_and_time = array(
                    'status'                 => $status_to,
                    'package_upload_user_id' => $_SESSION['current_account']['id'],
                    'package_upload_time'    => $this->nowtime,
                );
                break;
            default:
                $confirm_user_and_time = array(
                    'status' => $status_to,
                );
                break;
        }
        return $confirm_user_and_time;
    }


    public function delete()
    {
    }

    /**
     * @param array $_array
     * @param bool  $flag
     * @return mixed
     * 首页数据查询与显示
     */
    public function select($_array = array(),$flag = TRUE)
    {
        $_array = empty($_array)?$_GET:$_array;
        $model  = $this->Inboundshipmentplandetail->get_this_model($_array,$flag);

        if($flag){
            $Inboundshipmentplan_count = clone $model;
            $this->count               = $Inboundshipmentplan_count->count();//数量
            $Page                      = new \Org\Util\Page($this->count,20);// 实例化分页类 传入总记录数和每页显示的记录数(5)
            $this->page                = $Page->show();// 分页显示输出

            $model->order("create_time desc")
                ->limit($Page->firstRow.','.$Page->listRows);
        }
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $result     = $model->select();
        $result     = $this->format_inbound_detail_data($result,'fba_inbound_shipment_plan');
        $returndata = $this->format_index_data($result,$flag);
        foreach($returndata as $k =>$v){
            $returndata[$k]['fire'] = $this->checkFire(trim($v['id']));
        }
        return $returndata;
    }

    /**
     * @param $result
     * @return array
     * 拼接首页数据
     */
    public function format_index_data($result,$flag)
    {
        $return_result = array();
        $compliance_arr     = PublicInfoService::get_compliance_array();

        foreach($result as $key => $val){
            $return_result[$key]['id']                                 = $val['id'];
            $return_result[$key]['account_id']                         = $val['account_id'];
            $return_result[$key]['account_name']                       = $val['account_name'];
            $return_result[$key]['site_id']                            = $val['site_id'];
            $return_result[$key]['seller_id']                          = $val['seller_id'];
            $return_result[$key]['seller_name']                        = $val['seller_id']?PublicInfoService::get_user_name_by_id($val['seller_id']): $val['create_user_id'];
            $return_result[$key]['merchant_id']                        = $val['merchant_id'];
            $return_result[$key]['batch_code']                         = $val['batch_code'];
            $return_result[$key]['shipmentid']                         = $val['shipmentid'];
            $return_result[$key]['tranfer_hopper_id']                  = $val['tranfer_hopper_id'];
            $return_result[$key]['transport_plan_id']                  = $val['transport_plan_id'];
            $return_result[$key]['carrier_service_id']                 = $val['carrier_service_id'];
            $return_result[$key]['fnsku']                              = $val['fnsku'];
            $return_result[$key]['claim_arrive_time']                  = $val['claim_arrive_time'];
            $return_result[$key]['invoice_path']                       = $val['invoice_path'];
            $return_result[$key]['status']                             = $val['status'];
            $return_result[$key]['ship_from_address_id']               = $val['ship_from_address_id'];
            $return_result[$key]['destination_fullfillment_center_id'] = $val['destination_fullfillment_center_id'];
            $return_result[$key]['ship_to_address_id']                 = $val['ship_to_address_id'];
            $return_result[$key]['create_user_id']                     = $val['create_user_id'];
            $return_result[$key]['push_warehouse_user_id']             = $val['push_warehouse_user_id'];
            $return_result[$key]['create_time']                        = $val['create_time'];
            $return_result[$key]['package_print_user_id']              = $val['package_print_user_id'];
            $return_result[$key]['package_print_time']                 = $val['package_print_time'];
            $return_result[$key]['package_upload_user_id']             = $val['package_upload_user_id'];
            $return_result[$key]['package_upload_time']                = $val['package_upload_time'];
            $return_result[$key]['package_pdf_path']                   = $val['package_pdf_path'];
            $return_result[$key]['remark']                             = $val['remark'];
            $return_result[$key]['invoice_path']                       = $val['invoice_path'];
            $return_result[$key]['print_pick_note_user']               = $val['print_pick_note_user'];
            $return_result[$key]['print_pick_note_time']               = $val['print_pick_note_time'];

            $inbound_shipment_plan_id = $val['id'];
            $prepare_detail           = $this->Inboundshipmentplandetail->Inboundshipmentplandetail->where("inbound_shipment_plan_id={$inbound_shipment_plan_id}")
                ->select();

            $shipment_id = $val['shipmentid'];
            $compliance_detail = $this->Prepareneedsdetailsshipmentid->getComplianceInfo($shipment_id);

            foreach ($compliance_detail as $sku => &$compliance) {
                $com_arr = explode(',', $compliance['compliance']);
                $com_str = '';
                foreach ($com_arr as $val) {
                    $com_str .= "<b>" . $compliance_arr[$val] . "</b>,<br/>";
                }
                $com_str .= $compliance['comment'] ? '<b>备注:</b>' . $compliance['comment'] : '';
                $compliance['compliance'] = $com_str;
            }

            $prepare_detail           = $this->format_prepareneeds_data($prepare_detail);
            foreach($prepare_detail as $k => $detail){
                $return_result[$key]['detail'][$k]['id']                  = $detail['id'];
                $return_result[$key]['detail'][$k]['sku']                 = $detail['sku'];
                if(!$flag){
                    $return_result[$key]['detail'][$k]['image_url']           = $this->getSkuSystemImgData($detail['sku']);
                }
                $return_result[$key]['detail'][$k]['seller_sku']          = $detail['seller_sku'];
                $return_result[$key]['detail'][$k]['sku_name']            = $detail['sku_name'];
                $return_result[$key]['detail'][$k]['sku_virtual']         = $detail['sku_virtual'];
                $return_result[$key]['detail'][$k]['fnsku']               = $detail['fnsku'];
                $return_result[$key]['detail'][$k]['title']               = $detail['title'];
                $return_result[$key]['detail'][$k]['position']            = $detail['position']?$detail['position']:$this->findPosition($detail['sku'], $detail['export_tax_rebate'], $detail['enterprise_dominant']);//$detail['position'];
                $return_result[$key]['detail'][$k]['quantity']            = $detail['quantity'];
                $return_result[$key]['detail'][$k]['export_tax_rebate']   = $detail['export_tax_rebate'];
                $return_result[$key]['detail'][$k]['enterprise_dominant'] = $detail['enterprise_dominant'];
                $return_result[$key]['detail'][$k]['hs_code']             = $detail['hs_code'];
                $return_result[$key]['detail'][$k]['declaration_element'] = $detail['declaration_element'];
                $return_result[$key]['detail'][$k]['sku_cname']           = $detail['sku_cname'];
                $return_result[$key]['detail'][$k]['deliveryorders_id']   = $detail['deliveryorders_id'];
                $return_result[$key]['detail'][$k]['compliance'] = isset($compliance_detail[$detail['sku']]['compliance']) ?
                    $compliance_detail[$detail['sku']]['compliance'] : '';
            }

            /*$Page->parameter .= "$key=".urlencode($val).'&';*/
        }
        return $return_result;
    }
    /**
     * 描述 ： 通过CURL获取SKU基础资料数据
     */
    public function getSkuSystemImgData($sku) {
        $postData = array(
            "sku"        => $sku,
            "gallery_id" => '1',
            "type"       => "ALL",
            "all_type"   => "false",
            "url_type"   => 'http'
        );
        $url = 'http://skuimg.kokoerp.com/api/?c=api_pictureurl_urlservers&a=get_pictureurl';
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);

        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        $img = '';
        $output = json_decode(curl_exec($ch),true);
        if($output['status']==205){

        }
        foreach ($output[$sku] as $k =>$v){
            foreach ($v as $num){
                foreach ($num as $c){
                    $img = $c;
                }
            }
        }
        curl_close($ch);
        return $img?$img:'';
    }
    /*获取单个SKU图片*/
    public function getSkuImage($sku) {
        $image_url = '';
        $sku   = mysql_real_escape_string(strtoupper(trim($sku)));
        $sql   = "SELECT
              `file_name`
        FROM
              `image`
        WHERE
              `sku` = '$sku' AND `file_name` LIKE '%-TALL-%' LIMIT 1";
        $image = M("image", ' ', 'DB_SKU')->query($sql);
        if($image){
            $arr               = explode(".",$image[0]['file_name']);
            $image_url = URL::base(TRUE).'getimage/conversion_image/'.$arr[0];
        }
        if($image_url === '') {
            $sql = "SELECT products_id,products_imagess FROM erp_products_data WHERE `products_sku`='".$sku."'";
            $proArr = M("erp_products_data", ' ', 'DB_OLD_ERP')->query($sql);
            $pro = empty($proArr) ? array() : $proArr[0];
            //缩略图
            if($pro&&isset($pro['products_id'])&&$pro['products_id'])
            {
                $db_images_sql = "select * from erp_images where proid = ".$pro['products_id'];
                $img_arrs      = M("erp_images", ' ', 'DB_OLD_ERP')->query($db_images_sql);

                foreach($img_arrs as $arr){
                    if(stristr($arr['filename'],'-ALL')||stristr($arr['filename'],'-all')){
                        $image_url = $arr['filename'];
                        break;
                    }
                }

                if($image_url == ''){
                    foreach($img_arrs as $arr){
                        if(stristr($arr['filename'],'http')){
                            $image_url = $arr['filename'];
                            break;
                        }
                    }
                }
            }
        }
        return $image_url;
    }


    /**
     * @param $fileName  文件名
     * @param $title     表格头
     * @param $data      表格书数据
     *                   下载
     */
    public function action_down($fileName,$title,$data,$flag = 1)
    {    //$title开始为一维数组
        set_time_limit(0);
        ini_set('memory_limit','2048M');
        header('Content-Type: applicationnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$fileName);
        header('Cache-Control: max-age=0');
        $file  = fopen('php://output',"a");
        $limit = 1000;
        $calc  = 0;
        foreach($title as $v){
            $tit[] = iconv('UTF-8','GB2312//IGNORE',$v);
        }
        fputcsv($file,$tit);
        $data_down = $this->format_inbound_detail_data($data);
        foreach($data_down AS $key => $j){
            if($flag){
                $down = array(
                    $j['account_name'],
                    $j['status'],
                    $j['shipmentid'],
                    $j['batch_code'],
                    $j['site_id'],
                    $j['claim_arrive_time'],
                    $j['carrier_service_id'],
                    $j['ship_from_address_id'] = str_replace('<br/>',"\n",$j['ship_from_address_id']),
                    $j['ship_from_address_id'] = str_replace('<br/>',"\n",$j['ship_from_address_id']),
                    $j['destination_fullfillment_center_id'],
                    $j['create_user_id'],
                    $j['create_time'],
                );
            }else{
                $down = $j;
            }
            $calc++;
            if($limit==$calc){
                ob_flush();
                flush();
                $calc = 0;
            }
            foreach($down as $t){
                $tarr[] = iconv('UTF-8','GB2312//IGNORE',trim($t));
            }
            fputcsv($file,$tarr);
            unset($tarr);
        }
        unset($data);
        fclose($file);
        exit();
    }
    /**
     * @version FBA物流计划单下载
     * @param $fileName  文件名
     * @param $title     表格头
     * @param $data      表格书数据
     *               
     */
    public function action_down_other($fileName,$title,$data,$flag = 1)
    {  
//        $data_down = $this->format_inbound_detail_data_other($data);
//        print_r($data_down);
//        exit;
        //$title开始为一维数组
        set_time_limit(0);
        ini_set('memory_limit','2048M');
        header('Content-Type: applicationnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$fileName);
        header('Cache-Control: max-age=0');
        $file  = fopen('php://output',"a");
        $limit = 1000;
        $calc  = 0;
        foreach($title as $v){
            $tit[] = iconv('UTF-8','GB2312//IGNORE',$v);
        }
        fputcsv($file,$tit);
        $data_down = $this->format_inbound_detail_data_other($data);
        foreach($data_down AS $key => $j){
            if($flag){
                $down = array(
                    $j['shipmentid'],
                    $j['create_time'],
                    $j['account_name'],
                    $j['site_id'],
                    $j['ship_from_address_id'] = str_replace('<br/>',"\n",$j['ship_from_address_id']),
                    $j['ship_to_address_id'] = str_replace('<br/>',"\n",$j['ship_to_address_id']),
                    $j['destination_fullfillment_center_id'],
                    $j['seller_sku'],
                    $j['sku'],
                    $j['purchaseorders_id'],
                    $j['need_buyer_id'],
                    $j['sku_name'],
                    $j['sku_cname'],
                    $j['en_item'],
                    $j['hs_code'],
                    $j['export_tax'],
                    $j['logo'],
                    $j['type_number'],
                    $j['declaration_element'],
                    $j['weight'],//净重
                    $j['asweight'],//毛重
                    $j['volume'],
                    $j['quantity'],
                    $j['single_price'],
                    $j['money'],
                    $j['export_tax_rebate'],
                    $j['enterprise_dominant'],
                    $j['need_claim_arrive_time'],
                    $j['need_seller_id'],
                    $j['need_single_ship'],
                    $j['need_status'],
                    $j['transport_carrier_service_id'],
                    $j['need_create_user_id'],
                    $j['need_create_time'],
                    $j['need_seller_check_user_id'],
                    $j['need_seller_check_time'],
                    $j['need_logistic_check_user_id'],
                    $j['need_logistic_check_time'],
                    $j['need_remark'],
                    $j['need_cargo_grade'],
                    
                );
            }else{
                $down = $j;
            }
            $calc++;
            if($limit==$calc){
                ob_flush();
                flush();
                $calc = 0;
            }
            foreach($down as $t){
                $tarr[] = iconv('UTF-8','GB2312//IGNORE',trim($t));
            }
            fputcsv($file,$tarr);
            unset($tarr);
        }
        unset($data);
        fclose($file);
        exit();
    }

    /**
     * @param $id
     * @return mixed
     * 条形码打印
     */
    public function print_goods_code($id)
    {
        $condition = array('b.id' => $id);
        $field     = "a.shipmentid,a.status,a.site_id,b.id,b.sku,b.fnsku,b.quantity as num,b.title";
        $model     = $this->Inboundshipmentplandetail->get_detail_model($condition,$field);
        return $model->select();
    }

    /**
     * @param $id
     * @return mixed
     * 更新总重量  总体积 总
     */
    public function caculate_totalinfo_by_shipmentid($id)
    {
        $condition = array('id' => $id);

        $shipmentplan_status = $this->Inboundshipmentplandetail->Inboundshipmentplan->where($condition)
            ->getField('status');
        if($shipmentplan_status!=30){
            return FALSE;
        }else{
            $package_box_model = M('package_box','fba_','DB_FBAERP');
            $package_box_info  = $package_box_model->where(array('inbound_shipment_plan_id' => $id))
                ->field('length,width,height,weight')
                ->select();
            $total_package     = count($package_box_info);//总包裹数
            $total_weight      = 0;
            $total_capacity    = 0;
            foreach($package_box_info as $info){
                $total_weight += $info['weight'];//总重量
                $total_capacity += ($info['length']*$info['width']*$info['height']);//总体积
            }

            //更新数据
            $data = array(
                'total_package'  => $total_package,
                'total_weight'   => $total_weight,
                'total_capacity' => $total_capacity/1000000//转换单位
            );
            $res  = $this->Inboundshipmentplandetail->update($condition,$data);
            return !empty($res)?$res:false;
        }
    }

    /**
     * 打印箱唛贴
     */
    public function print_prepackage($condition)
    {
        $field = "a.shipmentid,a.id,a.account_id,a.status";
        $model = $this->Inboundshipmentplandetail->get_detail_model($condition,$field);
        return $model->select();
    }

    public function push_packing()
    {
    }

    public function upload_package()
    {
    }

    public function get_prepackge_label()
    {
    }


    /**
     * @param array  $_array
     * @param string $_param
     * 获取某些字段值
     */
    public function get_field_by_param($_array = array(),$_param = '*')
    {
        return $this->Inboundshipmentplandetail->get_field_by_param($_array,$_param);
    }

    /**
     * @param $data
     * @return mixed
     * 格式化数据
     */
    public function format_inbound_detail_data($data,$table = 'fba_inbound_shipment_plan')
    {
        //$company_arr       = PublicInfoService::get_company_array();
        $transport_way_arr = PublicInfoService::get_transport_way_array();
        $site_arr          = PublicInfoService::get_site_array();
        //格式化
        foreach($data as &$_data){
            $_data['create_user_id'] = PublicInfoService::get_user_name_by_id($_data['create_user_id']);
            $_data['print_pick_note_user'] = PublicInfoService::get_user_name_by_id($_data['print_pick_note_user']);
            $_data['push_warehouse_user_id'] = PublicInfoService::get_user_name_by_id($_data['push_warehouse_user_id']);
            $_data['status']         = PublicInfoService::get_inbound_status_array($table,$_data['status']);
            $_data['carrier_service_id']   = $transport_way_arr[$_data['carrier_service_id']];
            $_data['site_id']              = $site_arr[$_data['site_id']];
            $ship_from_address_id          = D('Api/Amazon/AccountSite','Service')->getShipFromAddress($_data['ship_from_address_id']);
            $_data['ship_from_address_id'] = $ship_from_address_id['addressStr'];

            $ship_to_address_id          = D('Api/Amazon/ShipToAddress','Service')->getShipToAddress($_data['ship_to_address_id']);
            $_data['ship_to_address_id'] = $ship_to_address_id['addressStr'];
        }
        return $data;
    }
    /**
     * @vesion 下载FBA物流计划单数据格式
     * @param $data
     * @return mixed
     */
    public function format_inbound_detail_data_other($data)
    {
        //$company_arr       = PublicInfoService::get_company_array();
//        $transport_way_arr = PublicInfoService::get_transport_way_array();
        $site_arr          = PublicInfoService::get_site_array();
        $company_arr = PublicInfoService::get_company_array();
        $needStatusArr=PublicInfoService::getNeedStatusArr('fba_prepare_needs_details','status');
        //格式化
        foreach($data as &$_data){
            $need_arr = PublicInfoService::getNeedInfo($_data['shipmentid'],$_data['sku']);
            $_data['site_id']= $site_arr[$_data['site_id']];
            $_data['export_tax_rebate']=$_data['export_tax_rebate']==1?'是':'否';
            $_data['enterprise_dominant']=$company_arr[$_data['enterprise_dominant']];
            $_data['logo'] = PublicInfoService::getLogo($_data['sku']);
            $_data['type_number'] = PublicInfoService::getTypeNumber($_data['sku']);
            $_data['need_create_time']=$need_arr['create_time'];
            $_data['need_single_ship']=$need_arr['single_ship']==1?'是':'否';
            $_data['need_status']=$needStatusArr[$need_arr['status']];
            $_data['need_seller_id']=PublicInfoService::get_user_name_by_id($need_arr['seller_id']);
            $_data['need_buyer_id']=PublicInfoService::get_user_name_by_id($need_arr['buyer_id']);
            $_data['need_remark']=$need_arr['remark'];
            $_data['transport_carrier_service_id']=  PublicInfoService::getTransportServiceName($_data['transport_plan_id']);
            $_data['need_claim_arrive_time']=$need_arr['claim_arrive_time'];
            $_data['need_create_user_id']=PublicInfoService::get_user_name_by_id($need_arr['create_user_id']);
            $_data['need_seller_check_user_id']=PublicInfoService::get_user_name_by_id($need_arr['seller_check_user_id']);
            $_data['need_seller_check_time']=$need_arr['seller_check_time'];
            $_data['need_logistic_check_user_id']=PublicInfoService::get_user_name_by_id($need_arr['logistic_check_user_id']);
            $_data['need_logistic_check_time']=$need_arr['logistic_check_time'];
            $_data['need_cargo_grade']=$need_arr['cargo_grade'];
            $_data['overseas_supervision']=  PublicInfoService::getOverseasSupervision($need_arr['sku'], $need_arr['site_id']);
            $ship_from_address_id          = D('Api/Amazon/AccountSite','Service')->getShipFromAddress($_data['ship_from_address_id']);
            $_data['ship_from_address_id'] = $ship_from_address_id['addressStr'];
            $ship_to_address_id          = D('Api/Amazon/ShipToAddress','Service')->getShipToAddress($_data['ship_to_address_id']);
            $_data['ship_to_address_id'] = $ship_to_address_id['addressStr'];
            $purchaseDetailArr=PublicInfoService::getPurchaseDetail($_data['purchaseorders_id']);
            if(!empty($purchaseDetailArr)){
                $_data['export_tax']=PublicInfoService::get_user_name_by_id($purchaseDetailArr['export_tax']);
            }else{
                $_data['export_tax']=0;
            }
            //品牌
            $_data['logo']=PublicInfoService::getLogo($_data['sku']);
            //型号
            $_data['type_number']=PublicInfoService::getTypeNumber($_data['sku']);
            //英文品名
            $_data['en_item']=PublicInfoService::getEnItem($_data['sku']);
            //净重
            $_data['weight']=PublicInfoService::getWeight($_data['sku']);
            //毛重
            $_data['asweight']=PublicInfoService::getAsWeight($_data['sku']);
            //体积
            $_data['volume']=PublicInfoService::getVolume($_data['sku']);
            
            
        }
        return $data;
    }

    public function format_prepareneeds_data($data)
    {
        $company_arr = PublicInfoService::get_company_array();
        //格式化
        foreach($data as &$_data){
            $_data['enterprise_dominant'] = $company_arr[$_data['enterprise_dominant']];
            $_data['export_tax_rebate']   = $_data['export_tax_rebate']==1?'是':'否';
        }
        return $data;
    }

    /**
     * @param $data
     * @return mixed
     * 获取平台计划单数据
     */
    public function get_Inboundshipmentplan_detail(&$_array = array())
    {
        $this->data = $this->Inboundshipmentplandetail->get_detail_model($_array,"*,a.id as aid")
            ->select();
        $this->data = $this->format_inbound_detail_data($this->data);
    }

    /**
     * 取消时更改prepare_needs_details_shipmentid表的状态
     */
    public function updata_prepare_needs_details_shipmentid($shipmentid)
    {
        $model = M('prepare_needs_details_shipmentid','fba_',$this->Inboundshipmentplandetail->_db);
        $where = array('shipmentid' => $shipmentid);
        $data  = array('status' => 20);
        return $model->where($where)
            ->save($data);
    }

    /**
     * @param $inboundShipmentPlanId
     * @return array|bool
     * 下载外箱贴所需数据归结
     */
    public function getShipmentInboundBoxInfo($inboundShipmentPlanId)
    {
        $inboundShipmentPlanInfo = $this->Inboundshipmentplandetail->get_field_by_param(array(
                'id'     => $inboundShipmentPlanId,
                'status' => array(
                    array(
                        'EGT',
                        30
                    ),
                    array(
                        'LT',
                        100
                    ),
                ),
            ));

        /*计划待装箱*/
        if(empty($inboundShipmentPlanInfo)){
            return array();
        }
        $inboundShipmentPlanInfo = $inboundShipmentPlanInfo[0];

        $inboundShipmentPlanDetails    = $this->Inboundshipmentplandetail->queryDetails(array(
                'inbound_shipment_plan_id' => $inboundShipmentPlanId,
            ));
        $inboundShipmentPackageBoxInfo = M('package_box','fba_','DB_FBAERP')
            ->where('inbound_shipment_plan_id = '.$inboundShipmentPlanId)
            ->select();

        $inboundShipmentPackageBoxDetails = M('package_box_details','fba_','DB_FBAERP')
            ->where('inbound_shipment_plan_id = '.$inboundShipmentPlanId)
            ->select();
        /*系统数据异常*/
        if(empty($inboundShipmentPlanDetails)||empty($inboundShipmentPackageBoxInfo)||empty($inboundShipmentPackageBoxDetails)
        ){
            return FALSE;
        }
        $info                 = array();
        $info['account_id']   = $inboundShipmentPlanInfo['account_id'];
        $info['site_id']      = $inboundShipmentPlanInfo['site_id'];
        $info['shipmentid']   = $inboundShipmentPlanInfo['shipmentid'];
        $info['shipmentName'] = $inboundShipmentPlanInfo['shipment_name'];
        $shipToAddress        = D('Api/Amazon/ShipToAddress','Service')->getShipToAddress($inboundShipmentPlanInfo['ship_to_address_id']);
        if(empty($shipToAddress)||empty($shipToAddress['CenterId'])){
            return FALSE;
        }
        $info['shipToAddressCenterId'] = $shipToAddress['CenterId'];
        $info['sellerSkuNum']          = count($inboundShipmentPlanDetails);
        $info['totalNum']              = 0;

        /*计划明细*/
        foreach($inboundShipmentPlanDetails as $planDetail){
            $_detail               = array();
            $_detail['sellerSku']  = $planDetail['seller_sku'];
            $_detail['title']      = $planDetail['title'];
            $_detail['fnsku']      = $planDetail['fnsku'];
            $_detail['externalId'] = '';
            $_detail['quantity']   = $planDetail['quantity'];
            $info['totalNum'] += $planDetail['quantity'];

            $info['planDetails'][$planDetail['seller_sku']] = $_detail;
        }

        /*填充ASIN*/
        $info['asin'] = D('Api/Amazon/AccountSellerSku','Service')->getAsinBySellerSku($info['account_id'],array_keys($info['planDetails']));

        /*装箱明细信息*/
        $boxDetails = array();
        foreach($inboundShipmentPackageBoxDetails as $boxDetail){
            $boxDetails[$boxDetail['seller_sku']][$boxDetail['package_box_id']] = $boxDetail['quantity'];
        }
        $info['packageDetails'] = $boxDetails;

        /*装箱数据*/
        foreach($inboundShipmentPackageBoxInfo as $package){
            $info['packages'][$package['id']] = $package;
        }

        krsort($info['planDetails']);
        return $info;
    }

    /**
     * @param $siteId
     * @return string
     *根据站点获取下载外箱贴模板文件
     */
    public function getSiteTemplateName($siteId)
    {
        $site = D('Api/Amazon/Sites','Service')->getSites($siteId);
        if($site=='US-United States'){
            return 'InboundBoxTemplate_America.xlsx';
        }elseif($site!='CN-China'){
            return 'InboundBoxTemplate_Europe.xlsx';
        }
    }

    /**
     * @return array
     * 根据planid获取详情
     */
    public function getPlanDetailForId($id)
    {
        if(empty($id)){
           return FALSE;
        }
        $data = M('inbound_shipment_plan','fba_','DB_FBAERP')->where("id = $id")->field('total_package as box,total_weight as weight')->find();
        if(!$data){
            return FALSE;
        }
        $sku =  M('inbound_shipment_plan_detail','fba_','DB_FBAERP')->where("inbound_shipment_plan_id = $id")->field('sku,quantity')->select();

        foreach($sku as $k =>$v){
            $sku[$k]['price'] = $this->getPriceForSku($v['sku']);
        }
        $data['sku'] = $sku;
        $add =  M('inbound_shipment_plan','fba_','DB_FBAERP')->where("id = $id")->field('ship_to_address_id,ship_from_address_id')->find();
        $shipToAddress = M('ship_to_address','api_','DB_FBAERP')->where("id = ".$add['ship_to_address_id'])->find();
        $data['shipToAddress']['name'] = $shipToAddress['Name'];
        $data['shipToAddress']['address'] = $shipToAddress['AddressLine1']."\n".$shipToAddress['AddressLine2']."\n".
            $shipToAddress['DistrictOrCounty'].$shipToAddress['City']." ".$shipToAddress['StateOrProvinceCode'].
            $shipToAddress['PostalCode']."\n".$shipToAddress['CountryCode']."(".$shipToAddress['CenterId'].")";
        $shipFromAddress = M('ship_from_address','amazonorder_','DB_FBAERP')->where("id = ".$add['ship_from_address_id'])->find();
        $data['shipFromAddress']['name'] = $shipFromAddress['Name'];
        $data['shipFromAddress']['address'] = $shipFromAddress['AddressLine1'].$shipFromAddress['AddressLine2'].' '.
            $shipFromAddress['District'].''.$shipFromAddress['City'].' '.$shipFromAddress['Province'].' '.
            $shipFromAddress['CountryCode'];
        if(!$data){
            return FALSE;
        }
        return $data;
    }
    /**
     * @return array
     * 根据sku获取sku的价格
     */
    public function getPriceForSku($sku)
    {
       $price = M('price','skusystem_','DB_FBAERP')->where("sku = '".$sku."'")->field('num')->find();
       if($price)
           return $price['num'];
       else
           return 0;
    }
    /**
     * 装箱查询数据
     */
    public function packageSelect($_array = array(),$flag = TRUE)
    {
        set_time_limit(0);
        $planModel = M('inbound_shipment_plan','fba_','DB_FBAERP');
        $packageModel = M('package_box','fba_','DB_FBAERP');
        $packageDetailModel = M('package_box_details','fba_','DB_FBAERP');
        $data = array();
        $admin = PublicInfoService::get_user_name_and_id();
        $_array = empty($_array)?$_GET:$_array;
        if($_array['shipmentid']){
            $plan = $planModel->where("shipmentid = '".$_array['shipmentid']."'")->field('id,account_name')->find();
            $planId = $plan['id'];
            if($planId){
                $data = $packageModel->where("inbound_shipment_plan_id = $planId")->select();
                foreach($data as $k => $v){
                    $data[$k]['shipmentid'] = $_array['shipmentid'];
                    $data[$k]['adder_id'] = $admin[$v['adder_id']];
                    $data[$k]['account_name'] = $plan['account_name'];
                    $data[$k]['packageDetail'] = $packageDetailModel->where("package_box_id = ".$v['id'])->select();
                }
            }
        }
        return $data;
    }
    /**
     * 粘贴防火标示
     * */
    public function doFire($str){
        $packageModel = M('package_box','fba_','DB_FBAERP');
        if($str){
            $data = array(
                'fire_alarm' => 1,
                'adder_id' => session('current_account.id')
            );
            $str = implode(',',$str);
            $result = $packageModel->where('id in ('.$str.')')->setField($data);
            if($result){
                return TRUE;
            }else{
                return FALSE;
            }
        }
    }
    /**
     * 删除装箱数据
     * */
    public function boxDel($data){
        $packageModel = M('package_box','fba_','DB_FBAERP');
        $packageDetailModel = M('package_box_details','fba_','DB_FBAERP');
        if($data){
            $str = implode(',',$data['id']);
            $result = $packageModel->where('id in ('.$str.')')->delete();
            if($result){
                $_where['shipmentid'] = $data['shipmentid'];
                $save['status'] = 20;
                $this->Inboundshipmentplan->update($_where,$save);
                $packageDetailModel->where('package_box_id in ('.$str.')')->delete();
                return TRUE;
            }else{
                return FALSE;
            }
        }
    }

    /**
     * 描述: 根据shipmentid和sku获取主体
     * 作者: kelvin
     */
    public function getEnterprise($id,$sku) {
        $planModel =  M('inbound_shipment_plan_detail', 'fba_', 'DB_FBAERP');
        if($id && $sku){
            $where = array(
                'inbound_shipment_plan_id' =>$id,
                'sku' =>$sku,
            );
            $result = $planModel->where($where)->getField('enterprise_dominant');
            return $result?$result:null;
        }
    }
    /*
     * 查询是否有防火标示的箱子
     * kelvin 2017-03-02
     * */
    public function checkFire($id){
        $packageModel = M('package_box','fba_','DB_FBAERP');
        $result = $packageModel->where("inbound_shipment_plan_id = $id AND fire_alarm = 1")->select();
        if($result){
            return 1;
        }else{
            return 0;
        }
    }
    /**
     * 添加修改打印捡货单人以及打印时间
     */
    public function updatePrint($ids)
    {
        $model = M('inbound_shipment_plan', 'fba_', 'DB_FBAERP');
        $where = "id in ({$ids})";
        $data = array(
            'print_pick_note_time' => date('Y-m-d H:i:s'),
            'print_pick_note_user' => session('current_account.id')
        );
        return $model->where($where)->setField($data);
    }

    /**
     * @param $skuStorageDominantStocks
     * @return array
     *
     */
    public function formatSkuStorageDominantStock ($skuStorageDominantStocks) {
        $re = array();
        foreach($skuStorageDominantStocks as $skuStockDetail) {
            !isset($re[$skuStockDetail['sku']][$skuStockDetail['export_tax_rebate']][$skuStockDetail['enterprise_dominant']][$skuStockDetail['storage_position']]) &&
            $re[$skuStockDetail['sku']][$skuStockDetail['export_tax_rebate']][$skuStockDetail['enterprise_dominant']][$skuStockDetail['storage_position']]
                = $skuStockDetail['all_available_quantity'];
        }

        return $re;
    }

    /**
     * 描述: 根据计划单id查询计划单的详细sku及需求库存数量
     * 作者: kelvin
     */
    public function getSkuDetailByShipmentId($id) {

        $enterpriseDominants = PublicInfoService::get_company_array();
        $model = M('inbound_shipment_plan_detail', 'fba_', 'DB_FBAERP');
        $planModel = M('inbound_shipment_plan', 'fba_', 'DB_FBAERP');
        $site_id = $planModel->where("id='$id'")->getField('site_id');
        $site_arr = PublicInfoService::get_site_array();
        $site_name = $site_arr[$site_id];
        $skuDetails = $model->where("inbound_shipment_plan_id = '$id' and quantity !=0")
            ->getField('seller_sku, sku, id, quantity,fnsku, export_tax_rebate, enterprise_dominant');

        $skus = $model->where("inbound_shipment_plan_id = '$id' and quantity !=0")
            ->getField('sku', true);

        if (empty($skuDetails)) {
            return array(
                'status' => 501,
                'msg' => '平台计划单明细为空，请联系IT',
            );
        }
        $skuStorageStocks = $this->StockInModel->get_storage_inventories('', array_unique($skus),'',$site_id)->order('id ASC')->select();
        if (empty($skuStorageStocks)) {
            return array(
                'status' => 502,
                'msg' => '当前sku库存为空，请联系IT',
            );
        }
        $skuStorageStocks = $this->formatSkuStorageDominantStock($skuStorageStocks);

        foreach ($skuDetails as &$skuDetail) {
            $skuDetail['enterpriseDominantsName'] =
                isset($enterpriseDominants[$skuDetail['enterprise_dominant']]) ? $enterpriseDominants[$skuDetail['enterprise_dominant']] : '';

            $needStock = $skuDetail['quantity'];
            if (!empty($skuStorageStocks[$skuDetail['sku']][$skuDetail['export_tax_rebate']][$skuDetail['enterprise_dominant']])) {
                $currentSkuStorageStocks = $skuStorageStocks[$skuDetail['sku']][$skuDetail['export_tax_rebate']][$skuDetail['enterprise_dominant']];
                $meetFlag = 0;
                foreach ($currentSkuStorageStocks as $storage=>$stock) {
                    if (!$meetFlag && $needStock - $stock > 0) {
                        $skuDetail['stock'][$storage]['advise_quantity'] = $stock;
                        $skuDetail['stock'][$storage]['available_quantity'] = $stock;
                        $needStock = $needStock - $stock;
                    } else {
                        if (!$meetFlag) {
                            $skuDetail['stock'][$storage]['advise_quantity'] = $needStock;
                            $skuDetail['stock'][$storage]['available_quantity'] = $stock;
                            $meetFlag = 1;
                            continue;
                        }

                        $skuDetail['stock'][$storage]['available_quantity'] = $stock;
                        $skuDetail['stock'][$storage]['advise_quantity'] = 0;
                    }
                }
            } else {
                return array(
                    'status' => 503,
                    'msg' => $skuDetail['sku'] . ':' . ($skuDetail['export_tax_rebate'] == 0 ? '非出口退税' : '出口退税') .
                        '或当前' . $skuDetail['enterpriseDominantsName'] . '主体或当前'.$site_name.'站点没有库存',
                );
            }
        }
        return $skuDetails;
    }

    /**
     * 描述: 捡货确认
     * 作者: kelvin
     */
    public function savePickSku($data) {
        if (!is_array($data)) {
            return FALSE;
        }
        $shipmentPlanDetailModel = M('inbound_shipment_plan_detail', 'fba_', 'DB_FBAERP');
        //$shipmentPickingModel = M('inbound_shipmentid_picking', 'fba_', 'DB_FBAERP');
        $stockOut = D('Warehouse/StockOut', 'Service');
        $stockOutList = array();
        $result = array();
        $msg = array();
        foreach ($data as $k => &$_array) {
            $stockOutList['op_time'] = date('Y-m-d H:i:s',time());
            $stockOutList['delivery_department'] = $_array['accountName'];
            $stockOutList['export_tax_rebate'] = $_array['export_tax_rebate'];
            $stockOutList['enterprise_dominant'] = $_array['enterpriseDominantsName'];
            $stockOutList['delivery_man'] = $_SESSION['current_account']['id'];
            $stockOutList['sku'] = $_array['sku'];
            $stockOutList['sku_name'] = PublicInfoService::getSkuCnname_bak(trim($_array['sku']));
            $stockOutList['sku_standard'] = ' ';
            $stockOutList['storage_position'] = $_array['pick_storage'];
            $stockOutList['quantity'] = $_array['pick_quantity'];
            $stockOutList['site_id'] = $_array['site_id'];
            $stockOutList['seller_id'] = $_array['seller_id'];
            $stockOutList['internationalship_cost'] = ' ';
            $stockOutList['remark'] = ' ';
            $stockOutList['type'] = 10;
            $stockOutList['shipmentid'] = $_array['shipmentid'];
            $stockOutList['package_box_id'] = ' ';
            $stockOutList['fnsku'] = $_array['fnsku'];
            $stockOutList['hs_code'] = PublicInfoService::getSkuHsCode(trim($_array['sku']))?PublicInfoService::getSkuHsCode(trim($_array['sku'])):' ';
            $stockOutList['declaration_element'] = ' ';
            $result[] = $stockOutList;
        }
        $return = $stockOut->create_deliveryorders_by_picking_list($result);
        if ($return['status'] == 200) {
            foreach ($data as $k => $item) {
                $id = $item['inbound_shipment_plan_details_id'];
                $arr['deliveryorders_id'] = $return['message'][$item['fnsku']];
                $arr['position'] = $this->arrayFormat($item['pick_storage']);
                if (!$shipmentPlanDetailModel->where("id = '$id'")->setField($arr)) {
                    $msg[] = 400;
                }
                unset($detailId);
                $data[$k]['pick_storage'] = json_encode($item['pick_storage']);
                $data[$k]['deliveryorders_id'] = $return['message'][$item['fnsku']];
            }
            //$shipmentPickingModel->addAll($data);
            return $msg;
        } else {
            return $return['message'];
        }
    }

    /**
     * 描述: 查询平台计划单状态
     * 作者: kelvin
     */
    public function getStatus($id) {
        if ($id) {
            return M('inbound_shipment_plan', 'fba_', 'DB_FBAERP')->where("id = '$id'")->field('status')->find();
        }
    }

    /**
     * 描述: 根据平台计划单详情id查询相对的数据
     * 作者: kelvin
     */
    public function backShipmentIdSave($data) {
        if ($data) {
            $shipmentBackModel = M('shipment_back', 'fba_', 'DB_FBAERP');
            return $shipmentBackModel->addAll($data);
        }
    }

    /**
     * 描述: 判断返仓是否已存在
     * 作者: kelvin
     */
    public function checkBackShipment($shipmentId, $sku) {
        $shipmentBackModel = M('shipment_back', 'fba_', 'DB_FBAERP');
        $data = array(
            'shipmentid' =>$shipmentId,
            'sku' =>$sku
        );
        return $shipmentBackModel->where($data)->field('id')->find();
    }

    /**
     * 描述: 查询返仓列表
     * 作者: kelvin
     */
    public function selectBackShipment($data) {
        $shipmentBackModel = M('shipment_back', 'fba_', 'DB_FBAERP');
        $where = array();
        if (!empty($data['shipmentid'])) {
            $where['shipmentid'] = $data['shipmentid'];
        }
        if (!empty($data['id'])) {
            $where['id'] = $data['id'];
        }
        if (!empty($data['account_id'])) {
            $where['account_id'] = $data['account_id'];
        }
        if (!empty($data['back_status'])) {
            $where['back_status'] = $data['back_status'];
        }
        if (!empty($data['sku'])) {
            $where['sku'] = $data['sku'];
        }
        if (!empty($data['seller_id'])) {
            $where['seller_id'] = $data['seller_id'];
        }
        if (!empty($data['actual_back_time_from'])) {
            $where['actual_back_time'][] = array(
                'egt',
                $data['actual_back_time_from']
            );
        }
        if (!empty($data['actual_back_time_to'])) {
            $where['actual_back_time'][] = array(
                'elt',
                $data['actual_back_time_to']
            );
        }
        $result = $shipmentBackModel->where($where)->order('back_status asc')->select();
        $this->count               = count($result);//数量
        $Page                      = new \Org\Util\Page($this->count,20);// 实例化分页类 传入总记录数和每页显示的记录数(5)
        $this->page                = $Page->show();// 分页显示输出

        $result = $shipmentBackModel->where($where)->order("back_status asc")
            ->limit($Page->firstRow.','.$Page->listRows)->select();
        foreach ($result as $k =>$v) {
            $result[$k]['seller_name'] = PublicInfoService::get_user_name_by_id($v['seller_id']);
            $result[$k]['back_apply_user_name'] = PublicInfoService::get_user_name_by_id($v['back_apply_user_id']);
            $result[$k]['account_name'] = PublicInfoService::get_accounts_by_id($v['account_id'],'name');
            $result[$k]['enterprise_dominant_name'] = PublicInfoService::getCompanyName($v['enterprise_dominant']);
            $result[$k]['back_status_name'] = PublicInfoService::getNameForBackStatus('back_status',$v['back_status']);
        }
        return $result;
    }

    /**
     * 描述: 实物返仓分配储位保存
     * 作者: kelvin
     */
    public function saveBackShipment($id, $storage_json, $warehouse_id_str) {
        $shipmentBackModel = M('shipment_back','fba_', 'DB_FBAERP');
        $data['storage_json'] = $storage_json;
        $data['warehouse_id_str'] = $warehouse_id_str;
        $data['actual_back_user_id'] = $_SESSION['current_account']['id'];
        $data['actual_back_time'] = date('Y-m-d H:i:s', time());
        $data['back_status'] = 30;
        return $shipmentBackModel->where("id = '$id'")->setField($data);
    }

    /**
     * 描述: 根据shipmentId和Sku返回出库id
     * 作者: kelvin
     */
    public function getIdForShipmentIdAndSku($shipmentId, $sku) {
        $shipmentIdPicking = M('inbound_shipmentid_picking', 'fba_', 'DB_FBAERP');
        $data = array(
          'shipmentid' => $shipmentId,
          'sku' => $sku
        );
        $result = $shipmentIdPicking->where($data)->field('deliveryorders_id')->find();
        return $result?$result[0]['deliveryorders_id']:null;
    }
    /**
     * 描述: 数组转字符串
     * 作者: kelvin
     */
    public function arrayFormat($arr = array()) {
        $result = '';
        foreach ($arr as $k => $v) {
            $result .= $k.':'.$v.',';
        }
        return $result;
    }

    /**
     * @param $array
     * @return mixed
     * 描述：获取已经生成平台计划单的SKU的库存的占用量
     * 作者：橙子
     */
    public function occupiedInventoryGet($array) {
        $company = PublicInfoService::get_company_array();
        $status = PublicInfoService::get_inbound_status();

        $map = array();
        $map['plan.status'] = array('IN', '10,15');
        isset($array['account_id']) && $map['plan.account_id'] = $array['account_id'];
        isset($array['sku']) && $map['details.sku'] = $array['sku'];
        isset($array['export_tax_rebate']) && $map['export_tax_rebate'] = $array['export_tax_rebate'];
        isset($array['enterprise_dominant']) && $map['details.enterprise_dominant'] = $array['enterprise_dominant'];
        isset($array['shipmentid']) && $map['plan.shipmentid'] = $array['shipmentid'];

        $result = $this->Inboundshipmentplandetail->Inboundshipmentplandetail
            ->table('fba_inbound_shipment_plan_detail AS details')
            ->join('LEFT JOIN fba_inbound_shipment_plan AS plan ON details.inbound_shipment_plan_id = plan.id')
            ->field('details.sku,details.sku_name,details.quantity,details.export_tax_rebate,
                     details.enterprise_dominant,plan.status,plan.account_name,plan.seller_id,plan.shipmentid')
            ->where($map)
            ->select();

        if (!empty($result)) {
            foreach ($result as &$data) {
                $data['export_tax_rebate'] = $data['export_tax_rebate'] == 1 ? '是' : '否';
                $data['enterprise_dominant'] = $company[$data['enterprise_dominant']];
                $data['status'] = $status[$data['status']];
                $data['seller'] = PublicInfoService::get_user_name_by_id($data['seller_id']);

            }
        }

        return $result;

    }

    /**
     * 描述: 储位查找
     * 作者: kelvin
     */
    public function findPosition($sku = null, $export_tax_rebate = null, $enterprise_dominant = null) {
        $skuStorageStocks = $this->StockInModel
            ->get_storage_inventories('', array($sku, $export_tax_rebate,$enterprise_dominant))
            ->order('id ASC')->select();
        $result = '';
        if ($skuStorageStocks) {
            foreach ($skuStorageStocks as $k =>$v) {
                $result .= $v['storage_position'].' ：'.$v['all_available_quantity'].", \n";
            }
        }
        return $result;

    }
    /**
     * 描述: 不良申请查询
     * 作者: kelvin
     */
    public function moveSelect($data) {
        $moveModel = M('shipment_migrate', 'fba_', 'DB_FBAERP');
        $where = array();
        if (!empty($data['shipmentid'])) {
            $where['shipmentid'] = $data['shipmentid'];
        }
        if (!empty($data['account_id'])) {
            $where['account_id'] = $data['account_id'];
        }
        $result = $moveModel->alias('m')
            ->join('left join fba_inbound_shipment_plan a on a.shipmentid = m.ori_shipmentid')
            ->join('left join fba_inbound_shipment_plan_detail b on b.inbound_shipment_plan_id = a.id')
            ->field('a.shipmentid,b.sku,b.sku_name,b.quantity,b.export_tax_rebate,b.enterprise_dominant,m.aim_shipmentid,
                cur_needs_quantity,')
            ->where($where)
            ->select();
//        dump($result);die;
//        dump($moveModel->getlastSql());die;
        return $result;
    }
    /**
     * 描述: 根据计划单明细数量是否全部为空来修改计划单状态
     * 作者: kelvin
     */
    public function updateStatusForDetailQuantity($id) {
        if ($id) {
            //查询所有数据
            $where['inbound_shipment_plan_id'] = $id;
            //查询数量为0的数据
            $_array = array(
                'inbound_shipment_plan_id' =>$id,
                'quantity' =>0
            );
            $all = $this->Inboundshipmentplandetail->queryDetails($where);
            $del = $this->Inboundshipmentplandetail->queryDetails($_array);
            if (count($all) == count($del)) {
                $_where['id'] = $id;
                $save['status'] = 100;
                $this->Inboundshipmentplan->update($_where,$save);
            }
        }
    }
    public function shipmentIdRejectsList($data = array()) {
        $shipmentBackModel = M('shipment_rejects', 'fba_', 'DB_FBAERP');
        $where = array();
        if (!empty($data['shipmentid'])) {
            $where['shipmentid'] = $data['shipmentid'];
        }
        if (!empty($data['id'])) {
            $where['id'] = $data['id'];
        }
        if (!empty($data['account_id'])) {
            $where['account_id'] = $data['account_id'];
        }
        if (!empty($data['status'])) {
            $where['rejects_status'] = $data['status'];
        }
        if (!empty($data['sku'])) {
            $where['sku'] = $data['sku'];
        }
        if (!empty($data['seller'])) {
            $data['seller_id'] = PublicInfoService::get_user_id_by_name(trim($data['seller']));
            $where['seller_id'] = $data['seller_id'];
        }

        $result = $shipmentBackModel->where($where)->order('rejects_status asc')->select();
        $this->count               = count($result);//数量
        $Page                      = new \Org\Util\Page($this->count,20);// 实例化分页类 传入总记录数和每页显示的记录数(5)
        $this->page                = $Page->show();// 分页显示输出

        $result = $shipmentBackModel->where($where)->order("rejects_status asc")
            ->limit($Page->firstRow.','.$Page->listRows)->select();
        foreach ($result as $k =>$v) {
            $result[$k]['seller_name'] = PublicInfoService::get_user_name_by_id($v['seller_id']);
            $result[$k]['rejects_apply_user_name'] = PublicInfoService::get_user_name_by_id($v['rejects_apply_user_id']);
            $result[$k]['decision_user_name'] = PublicInfoService::get_user_name_by_id($v['decision_user_id']);
            $result[$k]['actual_do_user_name'] = PublicInfoService::get_user_name_by_id($v['actual_do_user_id']);
            $result[$k]['account_name'] = PublicInfoService::get_accounts_by_id($v['account_id'],'name');
            $result[$k]['enterprise_dominant_name'] = PublicInfoService::getCompanyName($v['enterprise_dominant']);
            $result[$k]['rejects_status_name'] = PublicInfoService::getNameForStatus('fba_shipment_rejects', 'rejects_status', $v['rejects_status']);
            $result[$k]['rejects_type_name'] = PublicInfoService::getNameForStatus('fba_shipment_rejects', 'rejects_type', $v['rejects_type']);
        }
        return $result;
    }
    /**
     * 描述: 不良处理销售选择
     * 作者: kelvin
     */
    public function rejectsSellerSave($id,$site_id,$type) {
        if (!$id) {
            $msg = array(
                'status' => 500,
                'msg' => 'id为空',
            );
            return $msg;
        }
        if (!$type) {
            $msg = array(
                'status' => 500,
                'msg' => '销售选择为空',
            );
            return $msg;
        }
        $rejects = $this->shipmentIdRejectsList(array('id'=>$id));
        if (!$rejects) {
            $msg = array(
                'status' => 500,
                'msg' => '数据错误',
            );
            return $msg;
        }
        if($type == 10) {
            $detail['quantity'] = $rejects[0]['ori_qty']-$rejects[0]['rej_qty'];
        }else{
            $detail['quantity'] = 0;
        }
        $where['id'] = $rejects[0]['inbound_shipment_plan_details_id'];
        $result = $this->Inboundshipmentplandetail->update_detail($where,$detail);
        if($result){
            $up = array(
                'decision_user_id' =>$_SESSION['current_account']['id'],
                'decision_time' =>date('Y-m-d H:i:s', time()),
                'rejects_type' =>$type,
                'rejects_status' =>20,
            );
            $da = M('shipment_rejects', 'fba_', 'DB_FBAERP')->where("id = '".$id."'")->setField($up);
            if($da) {
                if ($site_id == 107) {
                    $shipment_plan_id = $this->Inboundshipmentplandetail->queryDetails(array('id' => $where['id']));
                    $this->updateStatusForDetailQuantity($shipment_plan_id[0]['inbound_shipment_plan_id']);//检测并修改状态
                }
                $msg = array(
                    'status' => 200,
                    'msg' => '操作成功',
                );
                return $msg;
            }else{
                $msg = array(
                    'status' => 500,
                    'msg' => '操作失败',
                );
                return $msg;
            }
        }else {
            $msg = array(
                'status' => 500,
                'msg' => '操作失败',
            );
            return $msg;
        }

    }
    /**
     * 描述: 良品返仓处理
     * 作者: kelvin
     */
    public function rejectsBackSave($data = array()) {
        $sel['id'] = $data['id'];
        $warehouse_id_str = '';
        $flag = TRUE;
        $result = $this->shipmentIdRejectsList($sel);
        $plan_detail_id = $this->Inboundshipmentplandetail->queryDetails(array('id' => $result[0]['inbound_shipment_plan_details_id']));
        $position = $data['position'];
        $quantity = $data['quantity'];
        foreach($position as $k => $v) {
            $in[$k]['sku']  = $result[0]['sku'];
            $in[$k]['sku_name']  = $result[0]['sku_name'];
            $in[$k]['type']  = 80;
            $in[$k]['site_id']  = PublicInfoService::getSiteIdByAccountId($result[0]['account_id']);
            $in[$k]['storage_position']  = $v;
            $in[$k]['warehouse_quantity'] = $quantity[$k];
            $in[$k]['deliveryorders_id']  = $plan_detail_id[0]['deliveryorders_id'];
        }
        $stockIn = new StockInController();
        $inResult = $stockIn->Back_StockIn($in);
        if(count($inResult)==0){
            $flag = FALSE;
        }else{
            foreach ($inResult as $re) {
                $warehouse_id_str .= $re['id'].',';
            }
        }

        if ($flag) {
            $up = array(
                'actual_do_user_id'            => $_SESSION['current_account']['id'],
                'actual_do_time'               => date('Y-m-d H:i:s',time()),
                'warehouseorders_id'           => $warehouse_id_str?$warehouse_id_str:NULL,
//                'rejects_status'               => 30,
            );
            $da = M('shipment_rejects','fba_','DB_FBAERP')
                ->where("id = '".$data['id']."'")
                ->save($up);
            if ($da) {
                $this->badStatusUpdate($data['id']);
                $msg = array(
                    'status' => 200,
                    'msg'    => '操作成功',
                );
                return $msg;
            } else{
                $msg = array(
                    'status' => 500,
                    'msg'    => '操作失败',
                );
                return $msg;
            }
        }else{
            $msg = array(
                'status' => 500,
                'msg'    => '入良品仓分配储位失败',
            );
            return $msg;
        }
    }
    /**
     * 描述: 不良品返仓处理
     * 作者: kelvin
     */
    public function badProductsSave($data = array()) {
        $badModel = M('unqualified_deal_invoices','wms_','DB_FBAERP');
        $sel['id'] = $data['id'];
        $result = $this->shipmentIdRejectsList($sel);
        $bad['sku'] = $result[0]['sku'];
        $bad['warehouseid'] = 102;
        $bad['invoice_date'] = date('Y-m-d H:i:s');
        $bad['sku_name'] = $result[0]['sku_name'];
        $bad['site_id'] = $result[0]['site_id'];
        $bad['storage_position'] = $data['position']?$data['position']:' ';
        $bad['quantity'] = $result[0]['rej_qty'];
        $bad['export_tax_rebate'] = $result[0]['export_tax_rebate'];
        $bad['enterprise_dominant'] = $result[0]['enterprise_dominant'];
        $bad['quality_remark'] = $result[0]['remark'];
        $bad['operate_man'] = $_SESSION['current_account']['id'];
        $bad_id = $badModel->add($bad);
        if ($bad_id) {
            $up = array(
                'actual_do_user_id'            => $_SESSION['current_account']['id'],
                'actual_do_time'               => date('Y-m-d H:i:s',time()),
                'unqualified_deal_invoices_id' => $bad_id,
            );
            $da = M('shipment_rejects','fba_','DB_FBAERP')
                ->where("id = '".$data['id']."'")
                ->save($up);
            if ($da) {
                $this->badStatusUpdate($data['id']);
                $msg = array(
                    'status' => 200,
                    'msg'    => '操作成功',
                );
                return $msg;
            } else{
                $msg = array(
                    'status' => 500,
                    'msg'    => '操作失败',
                );
                return $msg;
            }
        }else{
            $msg = array(
                'status' => 500,
                'msg'    => '入不良品仓失败',
            );
            return $msg;
        }
    }
    /**
     * 描述: 不良品处理状态检测修改
     * 作者: kelvin
     */
    public function badStatusUpdate($id) {
        if($id){
            $result = $this->shipmentIdRejectsList(array('id'=>$id));
            if ($result[0]['unqualified_deal_invoices_id'] && $result[0]['unqualified_deal_invoices_id']){
                M('shipment_rejects','fba_','DB_FBAERP')
                    ->where("id = '$id'")
                    ->setField('rejects_status',30);
            }
        }
    }
    /**
     * 描述: 检查采购单和sku是否存在
     * 作者: kelvin
     */
    public function checkPuIdAndSku($puId,$sku) {
        $model = M('shipment_purchaseorder','fba_','fbawarehouse');
        $where = array(
            'warehouseorders_id' => trim($puId),
            'sku'              => trim($sku)
        );
        $data  = $model->where($where)
            ->find();
        if($data){
            return $data;
        }else{
            return FALSE;
        }

    }
    /**
     *  描述:根据shipmentid下载装箱信息
     *  作者:kelvin
     * */
    public function shipment_package_down($data = array())
    {
        if(empty($data)){
            echo "<script>alert('数据为空');history.go(-1);</script>";
        }else{
            set_time_limit(0);
            $where['shipmentid'] = array('in',$data);
            $where['status'] = array('in',array(30,40,50,60,70));
            $planModel = M('inbound_shipment_plan','fba_','DB_FBAERP');
            $ship = $planModel ->where($where)->getfield('shipmentid',true);
            $diff = array_diff($data,$ship);
            if(count($diff)>0){
                $msg = implode("\\n",$diff);
                echo "<script>alert('以下shipmentid不存在或者状态不符合,请核对后操作\\n".$msg."');history.go(-1);</script>";die;
            }
//            $packageModel = M('package_box','fba_','DB_FBAERP');
//            $packageDetailModel = M('package_box_details','fba_','DB_FBAERP');
            $result =  $planModel->alias('a')
                ->join('LEFT JOIN fba_package_box b ON b.inbound_shipment_plan_id = a.id')
                ->join('LEFT JOIN fba_package_box_details c ON c.package_box_id = b.id')
                ->join('LEFT JOIN fba_inbound_shipment_plan_detail d ON d.inbound_shipment_plan_id = c.inbound_shipment_plan_id AND c.seller_sku = d.seller_sku')
                ->join('LEFT JOIN skusystem_price e ON e.sku = c.sku')
                ->where($where)
                ->field('count(1) as num ,a.shipmentid,a.destination_fullfillment_center_id,group_concat(c.quantity) as quantityAll,
                a.site_id,b.length,b.width,b.height,b.weight,c.sku,c.package_box_id,c.sku_name,sum(c.quantity) as quantity,d.export_tax_rebate,d.enterprise_dominant,e.num as price,
                group_concat(c.sku) as skuAll,group_concat(c.sku_name SEPARATOR "@;@") as skuNameAll,group_concat(e.num) as priceAll')
                ->group('c.package_box_id')
                ->order('a.shipmentid,num asc')
                ->select();
            $arr = array();
            foreach ($result as $k => $v) {
                if(isset($arr[$v['shipmentid'].':'.$v['num'].':'.$v['skuAll']])){
                    $arr[$v['shipmentid'].':'.$v['num'].':'.$v['skuAll']]['boxNum']+=1;
                    $arr[$v['shipmentid'].':'.$v['num'].':'.$v['skuAll']]['quantity']+=$v['quantity'];
                    $arr[$v['shipmentid'].':'.$v['num'].':'.$v['skuAll']]['allweight']+=$v['weight'];
                    $arr[$v['shipmentid'].':'.$v['num'].':'.$v['skuAll']]['volume']+=($v['height']*$v['length']*$v['width'])/1000000;
                    if((int)$v['num']>1){
                        $arr[$v['shipmentid'].':'.$v['num'].':'.$v['skuAll']]['quantityAll'] .= ':'.$v['quantityAll'];
                    }

                }else{
                    $arr[$v['shipmentid'].':'.$v['num'].':'.$v['skuAll']] = $v;
                    $arr[$v['shipmentid'].':'.$v['num'].':'.$v['skuAll']]['boxNum'] = 1;
                    $arr[$v['shipmentid'].':'.$v['num'].':'.$v['skuAll']]['volume'] =$v['height']*$v['length']*$v['width']/1000000;
                    $arr[$v['shipmentid'].':'.$v['num'].':'.$v['skuAll']]['allweight']=$v['weight'];
                }
            }
            vendor('PHPExcel.PHPExcel');
            /*模板存放目录*/
//            dump($arr);die;
            $templateFile = realpath(__ROOT__) . '/Admin/Inbound/Template/' . date('Y-m-d',time());
            //$templateFile = '/var/www/fbawarehouse'. '/Admin/Inbound/Template/' . $templateFileName;
            $site = PublicInfoService::get_site_array();//站点
            $company = PublicInfoService::get_company_array();//主体
//            echo "<pre>";print_r($company);echo "</pre>";die;
            /*目标投放文件名*/
            $outputFileName = 'FBA装箱信息报表'.date('YmdHis').'.xlsx';
            $PHPExcel = new \PHPExcel();
            //$PHPReader = new \PHPExcel_Reader_Excel2007();
            $currentSheet = $PHPExcel->getSheet(0);
            $PHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $PHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $currentSheet->getColumnDimension('A')->setWidth(15);
            $currentSheet->getColumnDimension('D')->setWidth(15);
            $currentSheet->getColumnDimension('E')->setWidth(40);
            $currentSheet->getColumnDimension('L')->setWidth(35);
            $currentSheet->setCellValue('A1','SHIPMENTID');
            $currentSheet->setCellValue('B1','站点');
            $currentSheet->setCellValue('C1', '目的仓');
            $currentSheet->setCellValue('D1', "SKU");
            $currentSheet->setCellValue('E1', "SKU中文名称");
            $currentSheet->setCellValue('F1', "成本价");
            $currentSheet->setCellValue('G1', "数量");
            $currentSheet->setCellValue('H1', "箱数");
            $currentSheet->setCellValue('I1', "实重(KG)");
            $currentSheet->setCellValue('J1', "体积(M³)");
            $currentSheet->setCellValue('K1', "是否退税");
            $currentSheet->setCellValue('L1', "主体公司");
            $num = 2;
            foreach($arr as $k =>&$v){
                if((int)$v['num']==1){
                    $currentSheet->setCellValue('A'.$num, $v['shipmentid']);
                    $currentSheet->setCellValue('B'.$num, $site[$v['site_id']]);
                    $currentSheet->setCellValue('C'.$num, $v['destination_fullfillment_center_id']);
                    $currentSheet->setCellValue('D'.$num, $v['sku']);
                    $currentSheet->setCellValue('E'.$num, $v['sku_name']);
                    $currentSheet->setCellValue('F'.$num, $v['price']);
                    $currentSheet->setCellValue('G'.$num, $v['quantity']);
                    $currentSheet->setCellValue('H'.$num, $v['boxNum']);
                    $currentSheet->setCellValue('I'.$num, $v['allweight']);
                    $currentSheet->setCellValue('J'.$num, $v['volume']);
                    $currentSheet->setCellValue('K'.$num, $v['export_tax_rebate']==1?'是':'否');
                    $currentSheet->setCellValue('L'.$num, $company[$v['enterprise_dominant']]);
                    $num +=1;
                }else{
                    $list = explode(',',$v['skuAll']);
                    $qty = explode(':',$v['quantityAll']);
                    $price = explode(',',$v['priceAll']);
                    $name = explode('@;@',$v['skuNameAll']);

                    foreach($list as $key =>$val){
                        $quantity = 0;
                        foreach ($qty as &$d){
                            $q = explode(',',$d);
                            $quantity += $q[$key];
                        }

                        $currentSheet->setCellValue('A'.$num, $v['shipmentid']);
                        $currentSheet->setCellValue('B'.$num, $site[$v['site_id']]);
                        $currentSheet->setCellValue('C'.$num, $v['destination_fullfillment_center_id']);
                        $currentSheet->setCellValue('D'.$num, $val);
                        $currentSheet->setCellValue('E'.$num, isset($name[$key])?$name[$key]:0);
                        $currentSheet->setCellValue('F'.$num, isset($price[$key])?$price[$key]:0);
                        $currentSheet->setCellValue('G'.$num, $quantity);
                        if($key==0){
                            $currentSheet->setCellValue('H'.$num, $v['boxNum']);
                            $currentSheet->setCellValue('I'.$num, $v['allweight']);
                            $currentSheet->setCellValue('J'.$num, $v['volume']);
                            $currentSheet->mergeCells('H'.$num.':H'.($num+count($list)-1));
                            $currentSheet->mergeCells('I'.$num.':I'.($num+count($list)-1));
                            $currentSheet->mergeCells('J'.$num.':J'.($num+count($list)-1));

                        }
                        $currentSheet->setCellValue('K'.$num, $v['export_tax_rebate']==1?'是':'否');
                        $currentSheet->setCellValue('L'.$num, $company[$v['enterprise_dominant']]);
                        $num +=1;
                    }
                }

            }
            $PHPWriter = new \PHPExcel_Writer_Excel2007($PHPExcel);
            ob_start();
            header("Content-Type: application/force-download");
            header("Content-Type: application/octet-stream");
            header("Content-Type: application/download");
            header('Content-Disposition:attachment;filename="' .$outputFileName. '"');//输出模板名称
            header("Content-Transfer-Encoding: binary");
            header("Last-Modified:".gmdate("D, d M Y H:i:s")." GMT");
            header('Pragma: public');
            header('Expires: 30');
            header('Cache-Control: public');
            $PHPWriter->save('php://output');
            echo "<pre>";print_r($arr);echo "</pre>";die;
        }
    }
}